﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace M3u8Puller
{
    public class HttpHelper
    {
        public static string HttpStringDownload(string url)
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(
                (sender, certificate, chain, errors) =>
                {
                    return true;
                });

            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.Method = "GET";
            //request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36";
            request.Referer = url;
            request.Headers.Add("Upgrade-Insecure-Requests", "1");
            request.Timeout = 5 * 60 * 1000; // 5 minutes

            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream stream = response.GetResponseStream();

            MemoryStream buffer = new MemoryStream();

            int bye;
            while ((bye = stream.ReadByte()) != -1)
            {
                buffer.WriteByte((byte)bye);
            }
            stream.Close();
            byte[] bytes = buffer.ToArray();
            buffer.Close();

            Encoding encode = Encoding.UTF8;
            foreach (string head in response.Headers.AllKeys)
            {
                if (!head.ToLower().Equals("content-type"))
                {
                    continue;
                }
                string value = response.Headers.Get(head).Replace(" ", "");
                if (!value.ToLower().Contains("charset="))
                {
                    continue;
                }

                try { encode = Encoding.GetEncoding(value.Substring(value.IndexOf("charset=") + 8).Trim()); } catch { }

            }
            return encode.GetString(bytes);
        }

        public static byte[] HttpDownload(string url)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.Method = "GET";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3";
            //request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            request.Referer = url;
            request.Headers.Add("Upgrade-Insecure-Requests", "1");
            request.Timeout = 5 * 60 * 1000; // 5 minutes

            //在请求会出现基础连接已经关闭: 接收时发生意外错误的错误
            //一般原因是因为服务器不允许与 Internet 资源建立持久性连接连接和http的版本造成
            //request.KeepAlive = false;  //设置不建立持久性连接连接
            //request.ProtocolVersion = HttpVersion.Version10; //http的版本有2个,一个是1.0,一个是1.1 具体更具实际情况测试替换

            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream stream = response.GetResponseStream();

            MemoryStream buffer = new MemoryStream();

            int bye;
            while ((bye = stream.ReadByte()) != -1)
            {
                buffer.WriteByte((byte)bye);
            }
            stream.Close();
            byte[] bytes = buffer.ToArray();
            buffer.Close();
            return bytes;
        }

        public static byte[] HttpDownload2(string url)
        {
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Upgrade-Insecure-Requests", "1");
            webClient.Encoding = Encoding.UTF8;

            return webClient.DownloadData(url);
        }

        public string GetManyText(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/json";
            request.Accept = "application/json,text/javascript,*/*,q=0.01";
            request.Headers.Add("Accept-Encoding", "deflate,gzip");
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None;

            using (Stream stream = request.GetResponse().GetResponseStream())
            {
                StreamReader sr = new StreamReader(stream);
                return sr.ReadToEnd();
            }
        }

        public byte[] GetManyData(string url)
        {
            var text = GetManyText(url);
            return Encoding.UTF8.GetBytes(text);
        }
    }
}
